<template>
  <div>
    <a-form layout="inline" :form="form">
      <a-form-item>
        <a-range-picker
          v-model="form.dataTimeRange"
          :show-time="{ format: 'HH:mm:ss' }"
          format="YYYY-MM-DD HH:mm:ss"
          :placeholder="[$t('startTime'), $t('endTime')]"
        />
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="queryTrack" >{{$t('query')}}</a-button>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="startTrack" >{{$t('start')}}</a-button>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="pauseTrack" >{{$t('pause')}}</a-button>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="resumeTrack" >{{$t('continue')}}</a-button>
      </a-form-item>
      <a-form-item>
        <a-button type="primary" @click="stopTrack" >{{$t('stop')}}</a-button>
      </a-form-item>
      <a-form-item>
        <span>{{$t('accumulate')}}: {{ totalDistance.toFixed(0) }}Km</span>
        <span style="margin-left:20px;">{{$t('currentMileage')}}: {{ currentDistance.toFixed(2)  }}Km</span>
        <span style="margin-left:20px;">{{$t('speed')}}: {{ (currentSpeed*0.1).toFixed(2) }}Km/h</span>
      </a-form-item>
    </a-form>
    <a-slider
      v-model="trackProgress"
      @change="trackProgressChange"
      :max="path.length - 1"
      :trackStyle="{ backgroundColor: '#ff5733', height: '8px' }"
      :handleStyle="{ borderColor: '#ff5733', backgroundColor: '#ff5733', height: '20px', width: '20px' }"
    />
    <div class="map-wrapper">
      <div id="trackMap"></div>
      <ul id="myList" class="location-list">
        <li
          v-for="(point, index) in path"
          :key="index"
          :class="{ active: trackProgress === index }"
          :ref="'pointItem' + index"
        >
          <span>{{$t('position')}}: {{ index + 1 }}</span><br>
          <span>{{$t('longitude')}}: {{ point.lng }}</span><br>
          <span>{{$t('latitude')}}: {{ point.lat }}</span>
        </li>
      </ul>
    </div>
  </div>
</template>

<i18n>
  {
    "zh-CN": {
      "columns": {
        "startTime":"开始时间",
        "endTime":"结束时间",
        "query":"查询",
        "start":"开始",
        "pause":"暂停",
        "continue":"继续",
        "stop":"停止",
        "accumulate":"累计",
        "currentMileage":"当次里程",
        "speed":"车速",
        "position":"位置",
        "longitude":"经度",
        "latitude":"经度"
      }
    },
    "en-US": {
      "columns": {
        "startTime":"Start Time",
        "endTime":"End Time",
        "query":"Query",
        "start":"Start",
        "pause":"Pause",
        "continue":"Continue",
        "stop":"Stop",
        "accumulate":"Accumulate",
        "currentMileage":"Current Mileage",
        "speed":"Speed",
        "position":"Position",
        "longitude":"Longitude",
        "latitude":"Latitude"
      }
    },
    "fr-FR": {
      "columns": {
        "startTime":"Heure de début",
        "endTime":"Heure de fin",
        "query":"Enquête",
        "start":"Commencer",
        "pause":"Suspension",
        "continue":"Continuer",
        "stop":"Arrêter",
        "accumulate":"Cumulatif",
        "currentMileage":"Lorsque le Sous - kilométrage",
        "speed":"Vitesse du véhicule",
        "position":"Localisation",
        "longitude":"Longitude",
        "latitude":"Latitude"
      }
    }
  }
</i18n>

<script>
function isScriptAlreadyLoaded(srcCheck) {
  var scripts = document.getElementsByTagName('script');
  for (var i = 0; i < scripts.length; i++) {
      if (scripts[i].src.includes(srcCheck)) {
          return true;
      }
  }
  return false;
}
import { wgs84togcj02 } from 'gps-convert'
import { getAction, postAction } from '@api/manage';
import _ from 'lodash';
import * as dayjs from 'dayjs';
import moment from 'moment';
export default {
    name: 'EBikeMapTrack',
    props:{
      carCode: {
        type: String,
        default: ''
      },
      location:{
        type: Object,
        default: () => ({}),
      }
    },
    data() {
        return {
          totalDistance: 0,
          currentDistance: 0,
          currentSpeed: 0,
          trackProgress: 0,
          path: [
            { lat: 29.0544, lng: 119.4728 },
            { lat: 29.0545, lng: 119.4729 },
            { lat: 29.0546, lng: 119.473 },
            { lat: 29.0547, lng: 119.4731 },
            { lat: 29.0548, lng: 119.4732 },
            { lat: 29.0544, lng: 119.4728 },
            { lat: 29.0545, lng: 119.4729 },
            { lat: 29.0546, lng: 119.473 },
            { lat: 29.0547, lng: 119.4731 },
            { lat: 29.0548, lng: 119.4732 },
            { lat: 29.0544, lng: 119.4728 },
            { lat: 29.0545, lng: 119.4729 },
            { lat: 29.0546, lng: 119.473 },
            { lat: 29.0547, lng: 119.4731 },
            { lat: 29.0548, lng: 119.4732 },
            { lat: 29.0544, lng: 119.4728 },
            { lat: 29.0545, lng: 119.4729 },
            { lat: 29.0546, lng: 119.473 },
            { lat: 29.0547, lng: 119.4731 },
            { lat: 29.0548, lng: 119.4732 },
            { lat: 29.0544, lng: 119.4728 },
            { lat: 29.0545, lng: 119.4729 },
            { lat: 29.0546, lng: 119.473 },
            { lat: 29.0547, lng: 119.4731 },
            { lat: 29.0548, lng: 119.4732 },
            { lat: 29.0544, lng: 119.4728 },
            { lat: 29.0545, lng: 119.4729 },
            { lat: 29.0546, lng: 119.473 },
            { lat: 29.0547, lng: 119.4731 },
            { lat: 29.0548, lng: 119.4732 },
          ],
          form:{
            dataTimeRange: [
              moment().startOf('day').format('YYYY-MM-DD HH:mm:ss'), 
              moment().format('YYYY-MM-DD HH:mm:ss')
            ],
          },
          url: {
            trackUrl: "/rental/ebike/track-list",
          },
          ebikeMarker: null,
          speed: 500, //0.5秒移动一次ebikeMarker
          timer: null,
          moment,
          lis: [],
        }
    },
    created(){
      this.showMap();
    },
    mounted(){
      this.$nextTick(()=>{
        const ul = document.getElementById('myList');
        this.lis = ul.getElementsByTagName('li');
      })
    },
    watch:{
      carCode:{
        handler(val){
          this.trackList(val, null, null);
        },
        immediate: true,
        deep: true,
      }
    },
    methods: {
      queryTrack(){
        let startTime = dayjs(this.form.dataTimeRange[0]).format('YYYY-MM-DD HH:mm:ss');
        let endTime = dayjs(this.form.dataTimeRange[1]).format('YYYY-MM-DD HH:mm:ss');
      },
      startTrack(){
        this.move(0);
      },
      pauseTrack(){
        // 清除定时器
        clearInterval(this.timer);
      },
      resumeTrack(){
        this.move(this.trackProgress + 1);
      },
      stopTrack(){
        this.trackProgress = 0;
        clearInterval(this.timer);
        this.timer = null;
        this.moveMarker(this.path[this.trackProgress].lat, this.path[this.trackProgress].lng);
        this.scrollToActive();
      },
      trackProgressChange(value){
        const func = _.debounce(()=> {
          this.moveMarker(this.path[value].lat, this.path[value].lng);
          this.scrollToActive();
        }, 200);
        func();
      },
      trackList(carCode, startTime, endTime){
        const params = {
          carCode: carCode,
          startTime: startTime ? dayjs(startTime).format( 'YYYY-MM-DD HH:mm:ss') : dayjs().startOf('day').format( 'YYYY-MM-DD HH:mm:ss'),
          endTime: endTime ? dayjs(endTime).format('YYYY-MM-DD HH:mm:ss') : dayjs().format( 'YYYY-MM-DD HH:mm:ss'),
        };
        postAction(this.url.trackUrl, params).then((res) => {
          if (res.success) {
            this.path = JSON.parse(res.result);
            this.drawPolyline();
            this.$nextTick(()=>{
              const ul = document.getElementById('myList');
              this.lis = ul.getElementsByTagName('li');
            })
          }
        });
      },
      async loadScript() {
        const KEY = window._CONFIG['gMapKey'];
        const scriptSrc = `https://maps.googleapis.com/maps/api/js?libraries=geometry&key=${KEY}`;
        return new Promise((resolve, reject) => {
          if (isScriptAlreadyLoaded(scriptSrc)) {
            console.log('The script has already been loaded.');
            resolve(); 
          } else {
            const script = document.createElement("script");
            script.type = "text/javascript";
            script.src = scriptSrc;
            script.onload = () => {
              console.log('Script loaded successfully.', scriptSrc);
              resolve();
            };
            script.onerror = (error) => {
              console.error('Error loading script:', error);
              reject(error); 
            };
            document.body.appendChild(script);
          }
        });
      },
      async showMap(){
        await this.loadScript();
        if(!this.map){
          this.$nextTick(async () => {
            await this.initMap();
          })
        }
      },
      markerTemplate(status){
        let markerIcon;
        if(status){
          markerIcon = `/vehicle${status}.png`;
        }else{
          markerIcon = `/vehicle1.png`;
        }
        return markerIcon;
      },
      async initMap(){
        const lngLat = wgs84togcj02([this.location.longitude, this.location.latitude])
        this.map = new google.maps.Map(document.getElementById('trackMap'), {
            zoom: 12, // 设置地图缩放级别
            center: {lat: lngLat[1], lng: lngLat[0]}, 
        });
        const position = { lat: lngLat[1], lng: lngLat[0] };
        this.ebikeMarker = new google.maps.Marker({
          position: position,
          map: this.map,
          icon: {
            url: '/vehicle1.png', // 自定义图标URL
            scaledSize: new google.maps.Size(50, 50) // 设置图标大小（宽度和高度）
          }
        });

        this.drawPolyline();
      },
      moveMarker(newLat, newLng) {
        this.ebikeMarker.setPosition(new google.maps.LatLng(newLat, newLng));
      },
      move(index){
        if(!index || index === 0){
          this.trackProgress = 0;
          clearInterval(this.timer);
          this.timer = null;
        }
        this.timer = setInterval(() => {
          if(this.trackProgress <= this.path.length - 1){
            this.moveMarker(this.path[this.trackProgress].lat, this.path[this.trackProgress].lng);
            this.scrollToActive();
            this.trackProgress++;
          }else{
            //停止setInterval
            clearInterval(this.timer);
          }
        }, this.speed)
      },
      drawPolyline(){
        const polyline = new google.maps.Polyline({
          path: this.path,
          map: this.map,
          path: this.path,
          geodesic: true,
          strokeColor: '#FF0000',
          strokeOpacity: 1.0,
          strokeWeight: 2
        });
        
        // 创建起点Marker
        const startPoint = this.path[0]; 
        const startLatLng = {lat: startPoint.lat, lng: startPoint.lng };
        var startMarker = new google.maps.Marker({
          position: startLatLng,
          map: this.map,
          icon: {
            url: '/start.png', // 自定义图标URL
            scaledSize: new google.maps.Size(20, 20) // 设置图标大小（宽度和高度）
          },
          label: 'S', // 可以在Marker上显示一个标签，如'S'表示起点
        });
      
        // 创建终点Marker
        const endPoint = this.path[this.path.length - 1]; 
        const endLatLng = {lat: endPoint.lat, lng: endPoint.lng };
        var endMarker = new google.maps.Marker({
          position: endLatLng,
          map: this.map,
          icon: {
            url: '/end.png', // 自定义图标URL
            scaledSize: new google.maps.Size(20, 20) // 设置图标大小（宽度和高度）
          },
          label: 'E', // 可以在Marker上显示一个标签，如'E'表示终点
        });
      },
      scrollToActive() {
        const ul = document.getElementById('myList');
        for (let i = 0; i < this.lis.length; i++) {
          console.log("scrollToActive-------:", this.lis[i].classList);
          if (this.lis[i].classList.contains('active')) {
            const liTop = this.lis[i].offsetTop; // active li 的顶部相对于 ul 的顶部
            const ulHeight = ul.clientHeight; // ul 的可视高度
            const liHeight = this.lis[i].clientHeight; // active li 的高度

            // 计算需要滚动的距离
            const scrollTop = liTop - (ulHeight - liHeight) / 2;

            // 滚动到指定位置
            // ul.scrollTop = scrollTop;

            // 如果 active li 在顶部或底部附近，可能需要调整以避免超出边界
            if (scrollTop < 0) {
                ul.scrollTop = 0; // 滚动到顶部
            } else if (scrollTop + ulHeight > ul.scrollHeight) {
                ul.scrollTop = ul.scrollHeight - ulHeight; // 滚动到底部
            } else {
              ul.scrollTop = scrollTop; // 正常滚动
            }

            break; // 找到第一个 active 后退出循环
          }
        }
      },

    } 
}
</script>

<style lang="less" scoped>
.map-wrapper{
  width: 100%;
  height: 420px;
  display: flex;
  flex-direction: row;
  #trackMap{
    flex: 1;
  }
  .location-list{
    width: 200px;
    list-style: none;
    overflow-y: auto;
    padding: 10px;
    li {
      padding: 10px;
      border-bottom: 1px solid #ddd;
      &.active{
        background-color: #ffeb3b;
        font-weight: bold;
      }
    }
  }
}
</style>